package top.lilele.adminSystem.web;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.lilele.adminSystem.dto.CommonFileDto;
import top.lilele.adminSystem.entity.AdminFileEntity;
import top.lilele.adminSystem.service.AdminFileService;
import top.lilele.adminSystem.utils.BaseResponse;
import top.lilele.adminSystem.utils.ResponseCodeEnum;
import top.lilele.adminSystem.utils.Utils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lilele
 */
@RestController
@RequestMapping(value = "file")
@Slf4j
public class AdminFileController {
    @Resource
    AdminFileService adminFileService;

    /**
     * 单文件上传
     *
     * @param multipartFile 文件 必须参数
     * @param md5           文件md5
     * @param generateUrl   是否生成url 非必要参数 默认false
     * @return
     */
    @SneakyThrows
    @PostMapping(value = "upload")
    public BaseResponse upload(@RequestParam("file") MultipartFile multipartFile, @RequestParam(value = "md5") String md5, @RequestParam(value = "generateUrl", defaultValue = "false", required = false) Boolean generateUrl) {
        AdminFileEntity adminFileEntity = adminFileService.uploadFile(multipartFile, md5, generateUrl);
        return BaseResponse.info(ResponseCodeEnum.Success, adminFileEntity);
    }

    /**
     * 字节流下载文件
     *
     * @param commonFileDto
     * @param httpServletResponse
     */
    @PostMapping(value = "download")
    public void download(@RequestBody @Validated CommonFileDto commonFileDto, HttpServletResponse httpServletResponse) {
        adminFileService.download(commonFileDto.getFileId(), httpServletResponse);
    }

    /**
     * 生成唯一上传id
     *
     * @return
     */
    @PostMapping(value = "generateUploadId")
    public BaseResponse generateUploadId() {
        return BaseResponse.info(ResponseCodeEnum.Success, Utils.generateId());
    }

    /**
     * 获取文件的md5是否已经存在，用于秒传（PS：返回文件信息，则已经存在。返回null，不存在）
     *
     * @param md5
     * @return
     */
    @GetMapping("Md5Exist")
    public BaseResponse Md5Exist(@RequestParam("md5") String md5) {
        return BaseResponse.info(ResponseCodeEnum.Success, adminFileService.Md5Exist(md5));
    }
}
